import {
  defineStore
} from "pinia";
import {
  subLogin,
  getPermiList,
  getLUserInfo
} from '@/api/login.js'

// import {
//   constantRoute,
//   asyncRoutr,
//   anyRouter
// } from '@/router/routes.js'
import {
  constantRoute,
  asyncRoutr,
  anyRouter
} from '@/router/routes.js'
import router from "@/router/index";
import {
  scopy

} from '@/utils/common.js'

// 用于过滤当前用户需要展示的异步路由
function filterAsyncRoute(a, b) {
  return a.filter((item) => {
    if (b.includes(item.name)) {
      if (item.children && item.children.length > 0) {
        item.children = filterAsyncRoute(item.children, b)
      }
      return true;
    } else {
      return false;
    }
  });
}

export default defineStore("login", {
  state: () => {
    return {
      token: localStorage.getItem('token'),
      luser: localStorage.getItem('luser'),
      menulist: constantRoute,
      SIDEBAR_MENU_GROUP: JSON.parse(localStorage.getItem('SIDEBAR_MENU_GROUP')), // 侧边栏菜单组
      SIDEBAR_MENU: JSON.parse(localStorage.getItem('SIDEBAR_MENU')), //侧边栏菜单
      FILTER: JSON.parse(localStorage.getItem('FILTER')), //筛选条件
      BUTTON: JSON.parse(localStorage.getItem('BUTTON')), // 按钮
      user_info: '', // 用户信息
      childSys: localStorage.getItem('childSys'), // 系统
    };
  },
  actions: {
    // 用户登录
    async userLogin(login_data) {
      let result = await subLogin(login_data)
      if (result.code == 1) {
        this.token = result.data.token
        this.luser = result.data.luser
        localStorage.setItem('token', result.data.token)
        localStorage.setItem('luser', JSON.stringify(result.data.luser))
        this.getUserRouter()

        return 'ok'
      } else {
        return Promise.reject(new Error(result.msg))
      }
    },

    // 用户信息
    async userInfo() {
      let res = await getLUserInfo({})
      if (res.code == 1) {
        this.user_info = res.data.userAss.loginPhone
        localStorage.setItem('company', JSON.stringify(res.data.company))
        this.getUserRouter()
      } else {
        return Promise.reject(new Error(res.msg))
      }
    },
    // 路由
    async getUserRouter(e) {

      let res = await getPermiList({
        childSys: e ? e : this.childSys,
      })
      if (res.code == 1) {
        let data = res.data
        let SIDEBAR_MENU_GROUP_list = []
        let SIDEBAR_MENU_list = []
        let FILTER_list = []
        let BUTTON_list = []
        for (let i = 0; i < data.length; i++) {
          if (data[i].mType.key == 'SIDEBAR_MENU_GROUP') {
            SIDEBAR_MENU_GROUP_list.push(data[i].mName)
          }
          if (data[i].mType.key == 'SIDEBAR_MENU') {
            SIDEBAR_MENU_list.push(data[i].routeLink.split('@')[1])
          }
          if (data[i].mType.key == 'FILTER') {
            FILTER_list.push(data[i].mName)
          }
          if (data[i].mType.key == 'BUTTON') {
            BUTTON_list.push(data[i].mName)
          }
        }
        this.SIDEBAR_MENU_GROUP = SIDEBAR_MENU_GROUP_list
        this.SIDEBAR_MENU = SIDEBAR_MENU_list
        this.FILTER = FILTER_list
        this.BUTTON = BUTTON_list
        localStorage.setItem('SIDEBAR_MENU_GROUP', JSON.stringify(SIDEBAR_MENU_GROUP_list))
        localStorage.setItem('SIDEBAR_MENU', JSON.stringify(SIDEBAR_MENU_list))
        localStorage.setItem('FILTER', JSON.stringify(FILTER_list))
        localStorage.setItem('BUTTON', JSON.stringify(BUTTON_list))
        // 计算当前用户需要展示的异步路由   
        let userAsyncRoute = filterAsyncRoute(scopy(asyncRoutr), SIDEBAR_MENU_list)
        // console.log(userAsyncRoute, 'userAsyncRoute')
        // 菜单数据
        this.menulist = [...constantRoute, ...userAsyncRoute, ...anyRouter]
        // 注册异步路由和任意路由
        let arr_list = [...userAsyncRoute, ...anyRouter]
        arr_list.forEach((route) => {
          router.addRoute(route)
        })
        return 'ok'
      } else {
        let url = window.location.href
        let str1 = url.split('/#/')[1]
        if (url.includes('auth-bind-wx')) {

          return router.push(str1)
        } else if (url.includes('auth-bind-success')) {
          return router.push(str1)
        } else {
          return router.push('/login')
        }

        // return Promise.reject(new Error(res.msg))
      }
    }
  },
  getters: {},
});
